package cn.gs.filter;


import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

/**
 * 第一个过滤器(在web.xml中指定)，替换url中参数为properties中内容
 */
public class OutputReplaceFilter implements Filter {

    private Properties pp = new Properties();

    @Override
    public void init(FilterConfig filterconfig) throws ServletException {
        //获取web.xml中初始化参数
        String file = filterconfig.getInitParameter("file");
        //文件实际位置
        String realPath = filterconfig.getServletContext().getRealPath(file);
        System.out.println("第一个过滤器，初始化配置，文件实际位置： " + realPath);
        try {
            //加载非法词
            pp.load(new FileInputStream(realPath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doFilter(ServletRequest servletrequest,
                         ServletResponse servletresponse, FilterChain filterchain)
            throws IOException, ServletException {
        //自定义response
        WorkbenchInterfaceFilter response = new WorkbenchInterfaceFilter(
                (HttpServletResponse) servletresponse);
        //将自定义response传到servlet中
        filterchain.doFilter(servletrequest, response);
        //得到response输出内容
        String output = response.getCharArrayWriter().toString();
        //遍历敏感词
        for (Object obj : pp.keySet()) {
            String key = (String) obj;
            output = output.replace(key, pp.getProperty(key));
        }
        PrintWriter out = servletresponse.getWriter();
        //输出
        out.write(output);

    }

    @Override
    public void destroy() {
        pp = null;
    }
}
